<template>
	<div class="bg-white flex h-full">
		<!-- 项目切换 -->
		<div class="pt-16 pb-16 relative" style="border-right: 1px #eee solid; min-width: 16rem;">
			<div 
			class="absolute right-0 w-0.5 bg-blue-500 transition-all duration-300" 
			:style="`height: 3.375rem; top: ${cursorTop}rem`"
			v-if="this.index[0] === this.itemsIndex"
			></div>
			<div v-for="(item, index) in items[itemsIndex]" :key="index">
				<div 
				class="p-4 cursor-pointer text-center hover:text-blue-500 hover:bg-blue-50"
				@click="changeProjectInfo(item.project_id, index)" 
				:style="item.project_id === data.project_id ? 'color: rgba(74, 108, 231, 1' : ''"
				>{{item.project_name}}</div>
			</div>
			<!-- 点击切换 -->
			<div class="w-full flex items-center justify-between absolute left-0" style="top: 2rem;">
				<t-select class="w-20 ml-4" v-model="pageSize" :options="options" :onChange="pageSizeChane"></t-select>
				<div class="flex justify-between items-center mr-4">
					<t-button class="mr-4" variant="text" shape="circle" v-on:click="itemsIndex--" :disabled="itemsIndex === 0"><</t-button>
					<p class="text-gray-400"><span class="text-blue-500">{{itemsIndex + 1}}</span> / {{items.length}}</p>
					<t-button class="ml-4" variant="text" shape="circle" v-on:click="itemsIndex++" :disabled="itemsIndex >= (items.length - 1)">></t-button>
				</div>
			</div>
		</div>
		<!-- 项目信息 -->
		<div class="flex-grow">
			<div class="p-4">
				<div class="flex items-end mt-4">
					<h1 class="text-2xl" style="line-height: 1;">{{data.project_name}}</h1>
					<edit1-icon 
					class="ml-2 text-gray-400 cursor-pointer hover:text-blue-500" 
					size="medium" 
					@click="updateProject(data.project_id)"
					v-if="isButtonAuthority('编辑项目')"
					></edit1-icon>
				</div>
				<div class="flex mt-4">
					<div class="pt-1 pl-4 pr-4 pb-1 rounded" style="background-color: rgba(74, 108, 231, 0.2); color: rgba(74, 108, 231, 1);" v-if="data.project_type == 0">公司</div>
					<div class="pt-1 pl-4 pr-4 pb-1 rounded" style="background-color: rgba(74, 108, 231, 0.2); color: rgba(74, 108, 231, 1);" v-if="data.project_type == 1">客户</div>
					<div class="pt-1 pl-4 pr-4 pb-1 rounded ml-4" style="background-color: rgba(74, 108, 231, 0.2); color: rgba(74, 108, 231, 1);" v-if="data.project_type == 0">进行中</div>
					<div class="pt-1 pl-4 pr-4 pb-1 rounded ml-4" style="background-color: rgba(255, 141, 26, 0.2); color: rgba(255, 141, 26, 1);" v-if="data.project_type == 1">修改中</div>
					<div class="pt-1 pl-4 pr-4 pb-1 rounded ml-4" style="background-color: rgba(67, 207, 124, 0.2); color: rgba(67, 207, 124, 1);" v-if="data.project_type == 2">已完结</div>
					<div class="pt-1 pl-4 pr-4 pb-1 rounded ml-4" style="background-color: rgba(212, 48, 48, 0.2); color: rgba(212, 48, 48, 1);" v-if="data.project_type == 3">流单</div>
				</div>
				<div class="flex justify-between mt-8">
					<div class="flex">
						<div>
							<p>{{data.project_days}} 天</p>
							<p class="text-gray-400">项目周期</p>
						</div>
						<div class="ml-8">
							<p>{{data.project_leader_name}}</p>
							<p class="text-gray-400">项目组长</p>
						</div>
						<div class="ml-8">
							<p>{{data.project_service_name}}</p>
							<p class="text-gray-400">客服</p>
						</div>
						<div class="ml-8">
							<p>{{groups}}</p>
							<p class="text-gray-400">项目成员</p>
						</div>
					</div>
					<div class="flex">
						<t-popconfirm 
						v-model="deleteFileVisible" 
						theme="danger" 
						content="确认删除吗" 
						v-if="data.source_file && isButtonAuthority('上传源文件')"
						:onConfirm="deleteProjectFile"
						>
							<t-button variant="outline" theme="danger">删除文件</t-button>
						</t-popconfirm>
						<t-button class="ml-4" variant="outline" v-if="data.source_file" @click="fileDownload(data.source_file, data.project_name)">源文件下载</t-button>
						<div class="ml-4 w-80" v-if="!data.source_file && isButtonAuthority('上传源文件')">
							<t-upload
							v-model="flie"
							theme="file-input"
							placeholder="未选择文件"
							:requestMethod="requestMethod"
							showUploadProgress
							/>
						</div>
					</div>
				</div>
			</div>
			<t-divider></t-divider>
			<div class="p-4">
				<h2 class="text-lg">项目进度</h2>
				<t-steps :current="data.project_state" class="mt-4">
					<t-step-item title="项目启动" :content="data.project_start_date"></t-step-item>
					<t-step-item title="初稿提交" :content="data.project_first_date"></t-step-item>
					<t-step-item :title="data.project_state <= 2 ? '已完结' : '流单'" :status="stepStatus" :content="data.project_end_date"></t-step-item>
				</t-steps>
				<div class="flex mt-4" v-if="isButtonAuthority('控制项目进度')">
					<t-popconfirm v-if="data.project_state == 0" :onConfirm="projectFirstDraft" v-model="firstDraftValue" content="确认初稿已提交了吗" >
						<t-button>初稿提交</t-button>
					</t-popconfirm>
					<t-button variant="outline" v-if="data.project_state == 1" @click="openRewriteDialog">改稿延长</t-button>
					<t-popconfirm class="ml-4" v-if="data.project_state == 1" :onConfirm="projectEnd" v-model="endValue" content="确认该项目已完结了吗">
						<t-button>项目完结</t-button>
					</t-popconfirm>
					<t-popconfirm class="ml-4" v-if="data.project_state == 1" :onConfirm="projectFail" v-model="failValue" content="确认该项目流单了嘛QWQ" theme="danger">
						<t-button theme="danger">项目流单</t-button>
					</t-popconfirm>
				</div>
				<p class="text-gray-400 mt-4">注：</p>
				<p>本项目累计耗时 <span class="text-blue-500">{{data.project_days}}</span> 天，改稿延长次数 <span class="text-blue-500">{{data.amendment_no}}</span> 次。</p>
			</div>
			<t-divider></t-divider>
			<div class="p-4">
				<h2 class="text-lg">项目内容</h2>
				<p class="mt-2">{{data.project_body}}</p>
				<div class="flex justify-between mt-8 items-center">
					<h2 class="text-lg">相册</h2>
					<div class="flex">
						<t-button @click="deletePhotos" theme="danger" v-show="selectPhotosStatus"><delete-icon slot="icon"/>批量删除</t-button>
						<t-button class="ml-4" variant="text" @click="coseSelectPhotos" v-show="selectPhotosStatus "><check-rectangle-icon slot="icon"/>取消选择</t-button>
						<t-button variant="text" @click="selectPhotos" v-show="(!selectPhotosStatus && imgUrl.length > 0) && isButtonAuthority('删除项目相册')"><check-rectangle-icon slot="icon"/>选择作品</t-button>
						<t-button class="ml-4" variant="text" @click="openPhotoDialog" v-if="isButtonAuthority('上传项目相册')"><edit1-icon slot="icon"/>上传作品</t-button>
					</div>
				</div>
				<div class="mt-4 pb-8 justify-between" v-if="imgUrl.length != 0" style="grid-template-columns: repeat(auto-fill, 10rem); display: grid;">
					<t-image-viewer class="w-40 h-40 bg-gray-50" v-for="(img, index) in imgUrl" :key="img" :default-index="index" :images="imgUrl" v-show="!selectPhotosStatus">
						<template #trigger="{ open }">
							<div :class="`tdesign-demo-image-viewer__ui-image tdesign-demo-image-viewer__base`">
								<img alt="test" :src="img"  :class="`tdesign-demo-image-viewer__ui-image--img`"/>
								<div :class="`tdesign-demo-image-viewer__ui-image--hover`" @click="open">
									<span><browse-icon size="1.4em"/> 预览</span>
								</div>
								<div class="select-class" v-show="selectPhotosStatus"></div>
							</div>
						</template>
					</t-image-viewer>
					<div 
					class="w-40 h-40 bg-gray-50 select-class-base" 
					v-show="selectPhotosStatus" 
					v-for="(item, index) in imgData" 
					:key="index" 
					:style="item.selectValue ? 'border: 4px solid #4A6CE7;' : ''"
					@click="selectPhoto(item.project_images_id)"
					>	
						<div class="absolute w-full h-full flex items-center justify-center">
							<img alt="test" :src="serveHttp + item.project_image" style="width: auto; height: auto; max-width: 100%; max-height: 100%;"/>
						</div>
						<div 
						class="select-class flex justify-center items-center" 
						:style="item.selectValue ? 'border: 4px solid #4A6CE7; background-color: #4A6CE7;' : ''">
							<check-icon class="text-white" slot="icon" v-show="item.selectValue" size="30px"></check-icon>
						</div>
					</div>
				</div>
				<div class="text-gray-400" v-if="imgUrl.length === 0">当前相册暂无内容</div>
			</div>
		</div>
		<!-- 延长修改的弹窗 -->
		<t-dialog
		:visible.sync="lengthenDate"
		header="延长修改日期"
		:onConfirm="projectRewrite"
		:confirmBtn="{disabled: !this.dateStr, loading: confirmLoading}"
		width="380"
		>
			<t-date-picker v-model="dateStr" class="w-full pb-8" :disable-date="{ before: data.project_end_date }"/>
		</t-dialog>
		<!-- 相册管理弹窗 -->
		<t-dialog
		:visible.sync="photoDialog"
		header="相册管理"
		:onConfirm="closePhotoDialog"
		width="565"
		:confirmBtn="null"
		:cancelBtn="null"
		>
			<t-upload
			v-model="photoFlies"
			:action="`${serveHttp}/my/projectUploadSingle`"
			placeholder="支持批量上传图片文件"
			theme="image-flow"
			accept="image/*"
			multiple
			name="project_image"
			:headers="token"
			:auto-upload="false"
			:max="1000"
			:data="{project_id: data.project_id}"
			:onSuccess="photoSuccess"
			></t-upload>
		</t-dialog>
	</div>
</template>

<script>
	import { Edit1Icon, BrowseIcon, DeleteIcon, CheckRectangleIcon, CheckIcon } from 'tdesign-icons-vue'
	import SparkMD5 from 'spark-md5'
	import { getToken } from '@/unit/auth'
	import { serveHttp } from '@/unit/config'
	import { isButtonAuthority } from '@/unit/buttonAuthority'
	
	// 封装根据文件生成哈希的方法
	const changeBuffer = file => {
		return new Promise(resolve => {
			let fileReader = new FileReader()
			fileReader.readAsArrayBuffer(file.raw)
			fileReader.onload = ev => {
				let buffer = ev.target.result
				let spark = new SparkMD5.ArrayBuffer()
				let HASH
				let suffix
				spark.append(buffer)
				HASH = spark.end()
				suffix = /\.([a-zA-Z0-9]+)$/.exec(file.name)[1]
				resolve({
					buffer,
					HASH,
					suffix,
					filename: `${HASH}.${suffix}`
				})
			}
		})
	}
	
	export default {
		name: 'ProjectInfo',
		components: {
			Edit1Icon,
			BrowseIcon,
			DeleteIcon,
			CheckRectangleIcon,
			CheckIcon
		},
		data(){
			return {
				items: [],
				itemsIndex: 0,
				cursorTop: 1,
				data:{project_groups: []},
				imgUrl: [],
				pageSize: 20,
				index: [],
				options: [
					{value: 5, label: '5项'},
					{value: 10, label: '10项'},
					{value: 20, label: '20项'},
					{value: 50, label: '50项'},
					{value: 100, label: '100项'},
				],
				lengthenDate: false,
				dateStr: '',
				confirmLoading: false,
				flie: [],
				deleteFileVisible: false,
				firstDraftValue: false,
				endValue: false,
				failValue: false,
				photoDialog: false,
				photoFlies: [],
				serveHttp: '',
				selectPhotosStatus: false,
				imgData: []
			}
		},
		computed: {
			// 获取token设置请求头
			token() {
				let obj = {
					"Authorization": getToken()
				}
				return obj
			},
			// 把组员名字拼到一起
			groups(){
				let str = ''
				this.data.project_groups.map((item, index) => {
					if(index >= (this.data.project_groups.length - 1)){
						str = str + item.project_groups_name
					} else {
						str = str + item.project_groups_name + '、'
					}
				})
				return str
			},
			// 判断完结的状态
			stepStatus(){
				if(this.data.project_state === 3){
					return 'error'
				} else if(this.data.project_state === 2){
					return 'finish'
				} else {
					return ''
				}
			}
		},
		watch: {
			lengthenDate(newValue){
				if(!newValue){
					this.dateStr = ''
				}
			}
		},
		methods: {
			// 权限审核
			isButtonAuthority(str){
				return isButtonAuthority(str)
			},
			// 封装下载文件的方法
			fileDownload(url, fileName) {
				this.$store.dispatch('dashboard/fileDownload', url).then(res => {
					const link = document.createElement('a');
					let blob = new Blob([res], {
						type: 'application/pptx;chartset=UTF-8'
					});
					link.style.display = 'none';
					link.href = URL.createObjectURL(blob);
					const newFileName = fileName + '-项目源文件'
					const fileType = url.substring(url.lastIndexOf(".") + 1)
					link.setAttribute('download', newFileName + '.' + fileType);
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
					window.URL.revokeObjectURL(link.href);
				})
			},
			// 取消选择按钮
			coseSelectPhotos(){
				this.selectPhotosStatus = false
				this.imgData.forEach(item => {
					item.selectValue = false
				})
			},
			// 删除作品
			deletePhotos(){
				let body = { project_images_ids: '' }
				this.imgData.map(item => {
					if(item.selectValue){
						body.project_images_ids = body.project_images_ids + item.project_images_id + '@'
					}
				})
				if(body.project_images_ids === ''){ return this.$message.warning('请选择相片后再点击删除按钮') }
				body.project_images_ids = body.project_images_ids.slice(0, body.project_images_ids.length - 1)
				this.$store.dispatch('project/deleteProjectImage', body).then(res => {
					if(res.status === 0){
						this.$message.success('删除成功')
						let query = { project_id: this.data.project_id }
						this.getProjectBody(query)
					} else {
						this.$message.error(res.message)
					}
				})
			},
			// 选择作品
			selectPhoto(id){
				this.imgData.forEach(item => {
					if(id === item.project_images_id){
						item.selectValue = !item.selectValue
					}
				})
			},
			// 打开选择作品
			selectPhotos(){
				this.selectPhotosStatus = true
			},
			// 相册上传成功
			photoSuccess(context){
				if(context.results){
					this.$message.success('图片上传成功')
					let query = { project_id: this.data.project_id }
					this.getProjectBody(query)
				} else {
					this.$message.error('图片上传失败请稍后重试')
				}
			},
			// 点击相册管理弹窗确认按钮
			closePhotoDialog(){
				this.photoDialog = false
			},
			// 打开相册管理弹窗
			openPhotoDialog(){
				this.photoDialog = true
			},
			// 删除源文件
			deleteProjectFile(){
				const body = {
					project_id: this.data.project_id
				}
				this.$store.dispatch('project/deleteProjectFile', body).then(res => {
					if(res.status == 0){
						this.$message.success(res.message)
						let query = { project_id: this.data.project_id }
						this.getProjectBody(query)
					} else {
						this.$message.error(res.message)
					}
				})
			},
			// 源文件切片上传
			async requestMethod(file){
				let already = []
				let res = null
				let { HASH, suffix } = await changeBuffer(file)
				const query = { HASH }
				// 获取上传过的切片信息
				try{
					res = await this.$store.dispatch('project/projectUploadAlready', query)
					if(res.status == 0){
						already = res.fileList
					} else { 
						return this.$message.error(res.message)
					}
				} catch (err) {
					return this.$message.error(err)
				}
				// 对文件进行切片
				let max = 1024 * 100
				let count = Math.ceil(file.size / max)
				let index = 0
				let chunks = []
				if(count > 100){
					max = file.size / 100
					count = 100
				}
				while (index < count){
					chunks.push({
						file: file.raw.slice(index * max, (index + 1) * max),
						filename: `${HASH}_${index+1}.${suffix}`
					})
					index++
				}
				index = 0
				// 封装合并切片的请求
				const complate = async() => {
					if(index < count) return
					let body = { 
						HASH,
						count,
						project_id: this.data.project_id
					}
					let linshiData = null
					await this.$store.dispatch('project/projectUploadMerge', body).then(res => {
						if(res.status == 0){
							this.$message.success(res.message)
						}
						linshiData = res
					})
					return linshiData
				}
				let text = async () => {
					let data = null
					// promise封装上传切片函数
					let mulit = (chunk) => {
						return new Promise ((resolve, reject) => {
							let fm = new FormData
							fm.append('file', chunk.file)
							fm.append('filename', chunk.filename)
							this.$store.dispatch('project/projectUploadChunk', fm).then(async res => {
								if(index >= count){
									data = await complate()
									resolve(data)
								} else {
									resolve(res)
								}
							})
						})
					}
					// 对 chunks 进行 for循环, 循环发送请求
					for(let i = 0 ; i < chunks.length ; i++){
						index = i + 1
						file.percent = parseInt(100 * (index/chunks.length))
						if(already.length > 0 && already.includes(chunks[i].filename)){
							complate()
						}
						if(index < already.length) continue
						data =  await mulit(chunks[i])
					}
					return data
				}
				const results = await text()
				if(results.status == 0){
					let query = { project_id: this.data.project_id }
					this.getProjectBody(query)
					return {
						status: 'success',
						response: { url: results.servicePath }
					}
				} else {
					return {
						status: 'fail',
						error: '上传失败，请检查网络或稍后重试'
					}
				}
			},
			// 延长修改日期
			projectRewrite(){
				this.confirmLoading = true
				const query = { 
					project_id: this.data.project_id,
					project_rewrite_date: this.dateStr
				}
				this.$store.dispatch('project/projectRewrite', query).then(res => {
					if(res.status == 0){
						this.$message.success(res.message)
						this.getProjectBody(query)
					} else {
						this.$message.error(res.message)
					}
					this.confirmLoading = false
					this.lengthenDate = false
				})
			},
			// 打开延长修改窗口
			openRewriteDialog(){
				this.lengthenDate = true
			},
			// 项目流单
			projectFail(){
				const query = { project_id: this.data.project_id }
				this.$store.dispatch('project/projectFail', query).then(res => {
					if(res.status == 0){
						this.$message.success(res.message)
						this.getProjectBody(query)
					} else {
						this.$message.error(res.message)
					}
				})
			},
			// 项目完结
			projectEnd(){
				const query = { project_id: this.data.project_id }
				this.$store.dispatch('project/projectEnd', query).then(res => {
					if(res.status == 0){
						this.$message.success(res.message)
						this.getProjectBody(query)
					} else {
						this.$message.error(res.message)
					}
				})
			},
			// 初稿提交
			projectFirstDraft(){
				const query = { project_id: this.data.project_id }
				this.$store.dispatch('project/projectFirstDraft', query).then(res => {
					if(res.status == 0){
						this.$message.success(res.message)
						this.getProjectBody(query)
					} else {
						this.$message.error(res.message)
					}
				})
			},
			// 编辑项目
			updateProject(id){
				this.$router.push({
					name: 'UpdateProject',
					query: {
						project_id: id
					}
				})
			},
			// 配置改变的时候
			pageSizeChane(){
				const query = {project_id: this.data.project_id}
				this.getProjectBody(query)
			},
			// 当前项目的下标和对应是第几个数组
			dataIndex(){
				for(let i = 0 ; i < this.items.length ; i++){
					for(let j = 0 ; j < this.items[i].length ; j++ ){
						if(this.data.project_id == this.items[i][j].project_id){
							this.index = [i, j]
						}
					}
				}
			},
			// 改变对应项目信息
			changeProjectInfo(id){
				this.flie = []
				this.selectPhotosStatus = false
				if(id === this.data.project_id) return
				// 替换新query
				this.$router.replace({query: {project_id: id}});
				const query = {project_id: this.$route.query.project_id}
				this.getProjectBody(query)
			},
			// 获取项目信息
			getProjectBody(query){
				this.$store.dispatch('project/getProjectBody', query).then(res => {
					if(res.status == 0){
						// 处理 items ，对items进行分页
						this.items = res.data[1]
						let arrListNumber = 0
						if(this.items.length % this.pageSize === 0){
							arrListNumber = this.items.length / this.pageSize
						} else {
							arrListNumber = (Math.floor(this.items.length / this.pageSize)) + 1
						}
						let arr = []
						for(let j = 0 ; j < arrListNumber ; j++){
							arr[j] = []
							for(let i = (j * this.pageSize) ; i < ((j * this.pageSize) + this.pageSize) ; i++){
								if(i >= this.items.length){
									break
								}
								arr[j].push(this.items[i])
							}
						}
						this.items = arr
						// 修改项目信息
						this.data = res.data[0][0]
						// 修改项目相册信息
						this.imgUrl = []
						res.data[2].forEach(item => {
							this.imgUrl.push(this.serveHttp + item.project_image)
							item.selectValue = false
						})
						this.imgData = res.data[2]
						this.dataIndex()
						this.itemsIndex = this.index[0]
						this.cursorTop = (this.index[1] * 3.375) + 4
					}
				})
			}
		},
		created() {
			let query = { project_id: this.$route.query.project_id }
			this.getProjectBody(query)
			this.serveHttp = serveHttp
		}
	}
</script>

<style scoped>
	.tdesign-demo-image-viewer__ui-image {
		width: 100%;
		height: 100%;
		display: inline-flex;
		position: relative;
		justify-content: center;
		align-items: center;
		border-radius: var(--td-radius-small);
		overflow: hidden;
	}

	.tdesign-demo-image-viewer__ui-image--hover {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		left: 0;
		top: 0;
		opacity: 0;
		background-color: rgba(0, 0, 0, 0.6);
		color: var(--td-text-color-anti);
		line-height: 22px;
		transition: 0.2s;
	}

	.tdesign-demo-image-viewer__ui-image:hover .tdesign-demo-image-viewer__ui-image--hover {
		opacity: 1;
		cursor: pointer;
	}

	.tdesign-demo-image-viewer__ui-image--img {
		width: auto;
		height: auto;
		max-width: 100%;
		max-height: 100%;
		cursor: pointer;
		position: absolute;
	}

	.tdesign-demo-image-viewer__ui-image--footer {
		padding: 0 16px;
		height: 56px;
		width: 100%;
		line-height: 56px;
		font-size: 16px;
		position: absolute;
		bottom: 0;
		color: var(--td-text-color-anti);
		background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0) 100%);
		display: flex;
		box-sizing: border-box;
	}

	.tdesign-demo-image-viewer__ui-image--title {
		flex: 1;
	}

	.tdesign-demo-popup__reference {
		margin-left: 16px;
	}

	.tdesign-demo-image-viewer__ui-image--icons .tdesign-demo-icon {
		cursor: pointer;
	}

	.tdesign-demo-image-viewer__base {
		width: 160px;
		height: 160px;
		margin-bottom: 10px;
		border: 4px solid var(--td-bg-color-secondarycontainer);
		border-radius: var(--td-radius-medium);
	}
	
	.select-class{
		width: 24px;
		height: 24px;
		border: 4px solid var(--td-bg-color-secondarycontainer);
		border-radius: var(--td-radius-medium);
		position: absolute;
		top: 0;
		left: 0;
	}
	
	.select-class-base{
		position: relative;
		border: 4px solid var(--td-bg-color-secondarycontainer);
		border-radius: var(--td-radius-medium);
		margin-bottom: 10px;
		overflow: hidden;
		cursor: pointer;
		transition: all .5s;
	}
	
	.select-class-base:hover{
		border: 4px solid #A4B5F3;
		transform: translate(0, -10px);
		box-shadow: 5px 5px 10px 0px rgba(74, 108, 231, 0.2);
	}
</style>